<template>
  <div>
    <!-- 查询区域 -->
    <div class="card" style="margin-bottom: 5px">
      <el-card>
        <el-input
            style="width: 200px; margin-right: 10px"
            v-model="a_employee.name"
            placeholder="请输入名字查询"
            prefix-icon="Search"
        />
        <el-input
            style="width: 200px; margin-right: 10px"
            v-model="a_employee.id"
            placeholder="请输入ID查询"
            prefix-icon="Search"
        />
        <el-button type="primary" @click="load">查 询</el-button>
        <el-button type="warning" @click="reset">重 置</el-button>
      </el-card>
    </div>

    <!-- 操作按钮 -->
    <div class="card" style="margin-bottom: 5px">
      <el-button type="primary" @click="handleAdd">新 增</el-button>
      <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
    </div>

    <!-- 表格 -->
    <div class="card" style="margin-bottom: 5px">
      <el-table
          :data="a_employee.tableData"
          border
          style="width: 100%"
          stripe
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="编号" type="index" width="60"/>
        <el-table-column label="eid" prop="eid"/>
        <el-table-column label="姓名" prop="username"/>
        <el-table-column label="账号" prop="account"/>
        <el-table-column label="密码" prop="password"/>
        <el-table-column label="性别" prop="gender"/>
        <el-table-column label="年龄" prop="age"/>
        <el-table-column label="职位" prop="title"/>
        <el-table-column label="操作">
          <template #default="scope">
            <div><el-button type="primary" :icon="Edit" size="small" @click="handleEdit(scope.row)">编 辑</el-button>
    </div><el-button type="danger" :icon="Delete" size="small" @click="handleDelete(scope.row)">删 除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div style="margin-top: 20px; text-align: right;">
        <el-pagination
            @size-change="load"
            @current-change="load"
            v-model:current-page="a_employee.pageNumber"
            v-model:page-size="a_employee.pageSize"
            :page-sizes="[5, 10, 15, 20]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="a_employee.total"
            background
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="a_employee.form.eid ? '编辑员工' : '新增员工'" v-model="a_employee.formVisible" width="500">
      <el-form :model="a_employee.form" style="padding-right: 50px; padding-top: 20px;">
        <el-form-item label="姓名" label-width="80px">
          <el-input v-model="a_employee.form.username" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="账号" label-width="80px">
          <el-input v-model="a_employee.form.account" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item label="密码" label-width="80px">
          <el-input v-model="a_employee.form.password" placeholder="请输入密码" type="password" />
        </el-form-item>
        <el-form-item label="性别" label-width="80px">
          <el-radio-group v-model="a_employee.form.gender">
            <el-radio value="M" label="M">男</el-radio>
            <el-radio value="F" label="F">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄" label-width="80px">
          <el-input v-model="a_employee.form.age" placeholder="请输入年龄" type="number" />
        </el-form-item>
        <el-form-item label="职位" label-width="80px">
          <el-select v-model="a_employee.form.title" placeholder="请选择职位" style="width: 100%">
            <el-option label="管理员" value="管理员" />
            <el-option label="教练" value="教练" />
            <el-option label="普通员工" value="普通员工" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="a_employee.formVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { onMounted, reactive } from 'vue'
import request from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, Delete } from '@element-plus/icons-vue'
import { useRoute } from 'vue-router'

const a_employee = reactive({
  name: '',
  id: '',
  pageNumber: 1,
  pageSize: 10,
  total: 0,
  tableData: [],
  formVisible: false,
  form: {},
  selectedRows: [] // 用于存储用户选择的行数据
})

// 加载数据
const load = () => {
  request.get('/v1/admin/selectPage', {
    params: {
      tableName: 'employee',
      name: a_employee.name,
      id: a_employee.id,
      pageNum: a_employee.pageNumber,
      pageSize: a_employee.pageSize
    }
  }).then(res => {
    console.log('响应数据:', res);
    if (res.state === 2001) {
      a_employee.tableData = res.data.list || [];
      a_employee.total = res.data.total || 0;
    } else {
      a_employee.tableData = [];
      a_employee.total = 0;
    }
  }).catch(error => {
    console.error('请求失败:', error);
    a_employee.tableData = [];
    a_employee.total = 0;
  });
}

// 重置查询条件
const reset = () => {
  a_employee.name = ''
  a_employee.id = ''
  load()
}

// 处理新增
const handleAdd = () => {
  a_employee.form = {
    username: '',
    account: '',
    password: '',
    gender: 'M',
    age: '',
    title: '普通员工'
  };
  a_employee.formVisible = true;
}

// 处理编辑
const handleEdit = (row) => {
  a_employee.form = { ...row }; // 填充当前行数据
  a_employee.formVisible = true; // 打开对话框
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该员工吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    request.delete('/v1/admin/delete', {
      data: {
        tableName: 'employee',
        id: row.eid, // 使用 eid 作为删除的依据
      },
    }).then(res => {
      if (res.state === 2001) {
        ElMessage({
          message: '删除成功',
          type: 'success',
        });
        load(); // 重新加载数据
      } else {
        ElMessage({
          message: '删除失败',
          type: 'error',
        });
      }
    }).catch(error => {
      console.error('请求失败:', error);
      ElMessage({
        message: '请求失败，请检查网络或服务器',
        type: 'error',
      });
    });
  }).catch(() => {
    // 用户取消删除
  });
}

// 处理批量删除
const handleBatchDelete = () => {
  if (a_employee.selectedRows.length === 0) {
    ElMessage({ message: '请选择要删除的员工', type: 'warning' })
    return
  }

  ElMessageBox.confirm('确定要删除这些员工吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const ids = a_employee.selectedRows.map(row => row.eid) // 获取所有选中行的 eid
    request.delete('/v1/admin/batchDelete', {
      data: {
        tableName: 'employee',
        ids: ids // 传递要删除的 eid 列表
      }
    }).then(res => {
      if (res.state === 2001) {
        ElMessage({ message: '批量删除成功', type: 'success' })
        load() // 重新加载数据
      } else {
        ElMessage({ message: '批量删除失败', type: 'error' })
      }
    }).catch(error => {
      console.error('请求失败:', error)
      ElMessage({ message: '请求失败，请检查网络或服务器', type: 'error' })
    })
  }).catch(() => {
    // 用户取消删除
  })
}

// 处理用户选择的行数据
const handleSelectionChange = (rows) => {
  a_employee.selectedRows = rows
}

// 保存新增或编辑
const save = () => {
  const method = a_employee.form.eid ? 'put' : 'post'; // 判断是新增还是编辑
  const url = a_employee.form.eid ? '/v1/admin/update' : '/v1/admin/add';

  request[method](url, {
    tableName: 'employee',
    data: a_employee.form,
  }).then(res => {
    if (res.state === 2001) {
      ElMessage({
        message: a_employee.form.eid ? '编辑成功' : '新增成功',
        type: 'success',
      });
      a_employee.formVisible = false; // 关闭对话框
      load(); // 重新加载数据
    } else {
      ElMessage({
        message: a_employee.form.eid ? '编辑失败' : '新增失败',
        type: 'error',
      });
    }
  }).catch(error => {
    console.error('请求失败:', error);
    ElMessage({
      message: '请求失败，请检查网络或服务器',
      type: 'error',
    });
  });
}

// 初始化加载数据
load()
const route = useRoute()

onMounted(() => {
  const eid = route.params.eid
  if (eid) {
    a_employee.id = eid
    load()
  }
})
</script>

<style scoped>
.card {
  margin-bottom: 10px;
}
</style>
